﻿using Microsoft.Data.SqlClient;

namespace Infrastructure.Persistence;

public class SqlServerDataProvider : BoilerplateDataProvider
{
    public override bool CreateDatabaseIfNotExists(string connectionString)
    {
        (connectionString, var databaseName) = GetConnectionStringFormat(connectionString);

        // 检查数据库是否已经存在
        if (DatabaseExists(databaseName, connectionString))
        {
            Console.WriteLine($"Database '{databaseName}' already exists.");
            return false;
        }

        // 创建数据库的 SQL 查询字符串
        string createDatabaseQuery = $"CREATE DATABASE [{databaseName}]";

        using SqlConnection connection = new SqlConnection(connectionString) ;
        connection.Open();
        using SqlCommand command = new SqlCommand(createDatabaseQuery, connection);
        command.ExecuteNonQuery();

        Console.WriteLine($"Database '{databaseName}' created successfully.");

        return true;
    }

    public override bool DatabaseExists(string databaseName, string connectionString)
    {
        string query = "SELECT COUNT(*) FROM sys.databases WHERE name = @DatabaseName";

        using SqlConnection connection = new SqlConnection(connectionString);
        connection.Open();

        using SqlCommand command = new SqlCommand(query, connection);
        command.Parameters.AddWithValue("@DatabaseName", databaseName);

        return (int)command.ExecuteScalar() > 0;
    }
}
